package pop;

import javax.mail.internet.*;
import javax.mail.*;
import java.util.*;
import javax.activation.*;

/**
*
* 
*/
public class Conectar {
    
    //public String host = "pop.gmail.com";
    public String email;
    public String password;
    //static private int PORT = 995;
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    Properties props = System.getProperties();
    private Store store = null;
    private Folder activeFolder = null;
    

    public Conectar(String email, String password) {
        this.email = email;
        this.password = password;
    }
    
    public void connect()
       throws Exception {
    	
    	  //props.setProperty("mail.pop3.starttls.enable", "false");

          //props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
          
          //props.setProperty("mail.pop3.port","995");
          //props.setProperty("mail.pop3.socketFactory.port", "995");
          
    	  props.setProperty("mail.store.protocol","imaps");
    	  
          // Sesion
          Session session = Session.getInstance(props,null);
          //session.setDebug(true);
          store = session.getStore("imaps");
         
          // Conectar
          store.connect("imap.gmail.com", email, password);
         
          // Obtener mensajes de carpeta
          activeFolder = store.getFolder("INBOX");
        
          // Tipo
          activeFolder.open(Folder.READ_ONLY);
          
          System.err.println(activeFolder.getMessageCount());
          
          Message [] mensajes = activeFolder.getMessages();
          
          
//          for (int i=0;i<mensajes.length;i++)
//          {
//             System.out.println("From:"+mensajes[i].getFrom()[0].toString());
//             System.out.println("Subject:"+mensajes[i].getSubject());
//             System.err.println("gerardo masa");
//             if (mensajes[i].isMimeType("multipart/*"))
//             {
//                // Obtenemos el contenido, que es de tipo MultiPart.
//                Multipart multi;
//                multi = (Multipart)mensajes[i].getContent();
//                // Extraemos cada una de las partes.
//                for (int j=0;j<multi.getCount();j++)
//                {
//                   Part unaParte = multi.getBodyPart(j);
//                   if (unaParte.isMimeType("text/*"))
//                		   System.out.println(unaParte.getContent());
//                   }
//                }
//             }
             
          
    }
    
 
    
    public void disconnect() throws Exception{
       if (store != null) {
          activeFolder.close(true);
          store.close();
       }
    }
    
    public List listMails() throws Exception{
         return ReadMail.getMails(activeFolder.getMessages(12,13));
    }
}